//
//  HomeTableViewController.swift
//  dwdWb
//
//  Created by Dengdwd on 15/10/6.
//  Copyright © 2015年 dwd. All rights reserved.
//
let DWDSTATUSCELL = "DWDSTATUSCELL"
let DWDFOWARDCELL = "DWDFOWARDCELL"
import UIKit
import SVProgressHUD
import AFNetworking
import SDWebImage
class HomeTableViewController: BaseTableViewController,DWDCoverViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        if UserAcount.loadUserData() == nil {
            vistorView?.setUpVisitorUI("visitordiscover_feed_image_house", content: "关注一些人，回这里看看有什么惊喜", isHome: true)
            return
        }
        setUpNav()
        setUpTableView()

}
    
    
    
//    tableView基本数据
    private func setUpTableView() {
        tableView.registerClass(DWDFowardCell.self, forCellReuseIdentifier: DWDFOWARDCELL)
        tableView.registerClass(DWDNormalCell.self, forCellReuseIdentifier: DWDSTATUSCELL)
        tableView.estimatedRowHeight = 300
        tableView.rowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.tableFooterView = pullUpView
        self.refreshControl = UIRefreshControl()
        self.refreshControl?.addTarget(self, action: "loadStatuses", forControlEvents: UIControlEvents.ValueChanged)
        loadStatuses()
    }
//    菊花
    private lazy var pullUpView:UIActivityIndicatorView = {
    let pullUpView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    pullUpView.color = UIColor.redColor()
    return pullUpView
    }()
//    模型数组
    private lazy var statusModels = [DWDStatusModel]()
//    加载网络数据
    @objc private func loadStatuses() {
        let manager = AFHTTPSessionManager()
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        var params = [
            "access_token": UserAcount.loadUserData()!.access_token!
        ]
        if pullUpView.isAnimating(){
            if let statusModel = statusModels.last {
            params["max_id"] = "\(statusModel.status.id - 1)"}
        }else {
            if let statusModel = statusModels.first {
                params["since_id"] = "\(statusModel.status.id)"}
        }
        manager.GET(urlString, parameters: params, success: { (dataTask, result) -> Void in
            if let resultDic = result as? [String: AnyObject] {
                let statusDics = resultDic["statuses"] as? [[String: AnyObject]]
                var tempArray = [DWDStatusModel]()
                for statusDic in statusDics! {
                    let status = DWDStatuses(dict: statusDic)
                    let statusModel = DWDStatusModel(status:status)
                    tempArray.append(statusModel)
                }
                if self.pullUpView.isAnimating(){
                self.statusModels += tempArray
                }else{
                    if self.statusModels.count != 0 {
                        self.pullDownTips(tempArray.count)
                    }
                self.statusModels = tempArray + self.statusModels
                }
                self.cacheWebimage(self.statusModels, finish: {

                self.tableView.reloadData()
                })
            }
            self.endRefresh()
            }) { (dataTask, error) -> Void in
                printLog("错误信息:\(error)")
                SVProgressHUD.showInfoWithStatus("请求失败,你的网络不好")
                self.endRefresh()
        }
    }
//    设置单图缓存
    func cacheWebimage(array:[DWDStatusModel],finish:() ->()){
        var dataLen = 0
        let group = dispatch_group_create()
        for viewModel in array {
        let count = viewModel.thumbnailUrls?.count ?? 0
            if count != 1 {
            continue
            }
        dispatch_group_enter(group)
        SDWebImageManager.sharedManager().downloadImageWithURL(viewModel.thumbnailUrls![0], options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
            if image != nil {
            let data = UIImagePNGRepresentation(image)
            dataLen += data!.length
            }
            dispatch_group_leave(group)
        })
            dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
//            print("缓存图像完成 \(dataLen / 1024) K")
            finish()
            })
        }
    }
    
    
//    微博数据弹窗方法
    private func pullDownTips(count:Int) {
        if pullDownLabel.hidden == false {return}
        pullDownLabel.text = count == 0 ? "没有微博信息" : "有\(count)条新的微博信息"
        let height: CGFloat = 35
        pullDownLabel.hidden = false
        pullDownLabel.size = CGSize(width: SCREENW, height: height)
        pullDownLabel.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - height
        UIView.animateWithDuration(1, animations: { () -> Void in
         self.pullDownLabel.transform = CGAffineTransformMakeTranslation(0, height)
            }) { (finish) -> Void in
          UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
            self.pullDownLabel.transform = CGAffineTransformIdentity
            }, completion: { (finish) -> Void in
            self.pullDownLabel.hidden = true
          })
        }
    }
//    微博数据条数弹窗
    private lazy var pullDownLabel: UILabel = {
    let label = UILabel()
    label.text = "没有微博数据"
    label.backgroundColor = UIColor.orangeColor()
    label.font = UIFont.systemFontOfSize(14)
    label.textColor = UIColor.whiteColor()
    label.textAlignment = NSTextAlignment.Center
    self.navigationController?.view.insertSubview(label, belowSubview: self.navigationController!.navigationBar)
    label.hidden = true
    return label
    }()
    private func endRefresh() {
    self.pullUpView.stopAnimating()
    self.refreshControl?.endRefreshing()
    }
//设置导航栏
    private func setUpNav() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.item("navigationbar_friendsearch", target: self, action: "push")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.item("navigationbar_pop", target: self, action: "push")
        self.navigationItem.titleView = titleBtn
    }
//titleView
    private lazy var titleBtn: UIButton = {
        let btn = DWDButton()
        let account = UserAcount.loadUserData()
        btn.setTitle(account?.name ?? "首页", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected)
        btn.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        btn.sizeToFit()

        btn.addTarget(self, action: "clickTitleBtn:", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
//    titleView
    @objc private func clickTitleBtn(titleBtn:UIButton){
       
        self.setUpCover(titleBtn)
        
        titleBtn.selected = !titleBtn.selected
            
    }
//    弹窗
    private func setUpCover(titleBtn:UIButton) {
        let contentView = UIView()
        contentView.backgroundColor = UIColor.redColor()
        contentView.size = CGSizeMake(100, 100)
        let cover = DWDCoverView(customView:contentView)
        cover.delegate = self
        cover.show(titleBtn)
    }
    func coverViewMakeTitleRotate() {
        self.titleBtn.selected = false
    }
//    push控制器
    @objc private func push() {
        let tc = DWDTempViewController()
        self.navigationController?.pushViewController(tc, animated: true)
    }

}
//数据源方法
extension HomeTableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusModels.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let statusModel = self.statusModels[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(statusModel.cellID!, forIndexPath: indexPath) as! DWDStatusCell
        cell.statusModel = statusModel
        if indexPath.row == self.statusModels.count - 1 && !pullUpView.isAnimating() {
            pullUpView.startAnimating()
            loadStatuses()
        }
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let statusModel = self.statusModels[indexPath.row]
//        设置行高缓存
        if statusModel.rowHeight > 0 {
            return statusModel.rowHeight
        }
//       如果有预估高度会先调用indexPath方法 在调用这里 所以这个方法这么写防止循环引用
        let cell = tableView.dequeueReusableCellWithIdentifier(statusModel.cellID!) as! DWDStatusCell
        
        statusModel.rowHeight = cell.rowHeight(statusModel)
        
        return statusModel.rowHeight
    }

}